<?php
	
$data = array(
	array(
		'name' => 'jake',
		'score' => 80,
		'grade' => 'A'
	),
	array(
		'name' => 'jin',
		'score' => 70,
		'grade' => 'A'
	),
	array(
		'name' => 'john',
		'score' => 80,
		'grade' => 'A'
	),
	array(
		'name' => 'ben3',
		'score' => 203,
		'grade' => 'B3'
	)
);
 
$titleList = array('姓名', '总分', '等级');
$fileName = '高三(3)班 7 月份考试结果';
 csv_export($data, $titleList, $fileName);

 function csv_export(&$data, $titleList = array(), $fileName = '')
{
	ini_set("max_execution_time", "3600");
	$csvData = '';
 
	// 标题
	$nums = count($titleList);
	for ($i = 0; $i < $nums - 1; $i++)
	{
		$csvData .= '"' . $titleList[$i] . '",';
	}
	$csvData .= '"' . $titleList[$nums - 1] . "\"\r\n";
 
	foreach ($data as $key => $row)
	{
		$i = 0;
		foreach ($row as $_key => $_val)
		{
			$_val = str_replace("\"", "\"\"", $_val);
			if ($i < ($nums - 1))
			{
				$csvData .= '"' . $_val . '",';
			}
			elseif ($i == ($nums - 1))
			{
				$csvData .= '"' . $_val . "\"\r\n";
			}
			$i++;
		}
		unset($data[$key]);
	}

  	// $csvData = iconv('utf-8','gb2312',$csvData); // linux
	$csvData = mb_convert_encoding($csvData, "gb2312", "UTF-8"); // windows
	
	$fileName = empty($fileName) ? date('Y-m-d-H-i-s', time()) : $fileName;
	$fileName = $fileName . '.csv';
	header("Content-type:text/csv;");
	header("Content-Disposition:attachment;filename=" . $fileName);
	header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
	header('Expires:0');
	header('Pragma:public');
	echo $csvData;
	die();
}

?>